/* config */
import * as config from '@src/component/form/config';
import { isSelect, isMultiSelect, isInfo, isQuality } from './index';
import { isEmpty } from 'pub-bbx-utils';
import platform from '@src/platform'
/* service */
import { isLogisticsField } from '@service/FieldService'
import locales, { i18n, t } from '@src/locales'


/** 通用验证 */
function common(field){
  let message = [];
	  // 产品客户这边关联工单目前不可以编辑名称，因为英文下长度超出限制，所以暂时不做校验，如果之后有调整，需要注意~
    const isNoValid = field.formType === 'related_task' && ['product', 'customer'].includes(field.tableName)
    // 自定义字段验证名称长度
    if(field.isSystem == 0 && !isNoValid){
      if(field.displayName.length > config.FIELD_NAME_LENGTH_MAX) {
        message.push(t('common.validate.titleLimit', {limit: config.FIELD_NAME_LENGTH_MAX}))
      }
  }

  if(field.placeHolder && field.formType !== 'info' && field.placeHolder.length > config.FIELD_PLACEHOLER_LENGTH_MAX){
    message.push(t('common.validate.descriptionLimit', {limit: config.FIELD_PLACEHOLER_LENGTH_MAX}))
  }
  
  return message;
}

function select(field){
  let message = [];
  let { dataSourceType = 0 } = field?.setting || {};

  // 代码块的校验
  if (dataSourceType == 3) return relatedCode(field);

  let dataSource = (field.setting && field.setting.dataSource) || [];
  // 兼容多语言环境，取当前语言的数据
  const dataSourceLanguage = field.setting && field.setting.dataSourceLanguage
  if (dataSourceLanguage) {
    dataSource = dataSourceLanguage[locales.locale] || []
  }
  if (field.setting.dataType === 1) {
    if (field.setting.fieldNames.length == 0) message.push(t('common.validate.emptyOption'))
  } else {
    // 验证是否存在空值
    for(let i = 0; i < dataSource.length; i++){
      if(isEmpty(dataSource[i])){
        message.push(t('common.validate.emptyOption'))
        break;
      }
    }

    // 验证是否存在重复值
    // 验证选项字数
    for(let i = 0; i < dataSource.length; i++){
      let option = dataSource[i];
      if(option?.length > config.SELECT_OPTION_LENGTH_MAX){
        t('common.validate.optionWordsMax', {data1: i + 1, data2: config.SELECT_OPTION_LENGTH_MAX})
      }
      if(!isEmpty(option) && dataSource.lastIndexOf(option) != i){
        message.push(t('common.validate.repeatOption', {option}));
      }
    }

    // 验证选项数量
    const MAX = field?.setting?.customizedSelectOptionMax || config.SELECT_OPTION_MAX;
    if(dataSource.length > MAX){
      message.push(t('common.validate.optionNumMax', {max: MAX}));
    }
  }

  return message;
}

function logistics(field) {
  let message = [];
  let setting = field?.setting || {};
  let dataSource = setting?.dataSource || []
  
  if (setting?.dataSourceType == 1) {
    
    for(let i = 0; i < dataSource.length; i++){
      
      if (!(dataSource[i]?.id)) {
        
        message.push(t('common.validate.emptyOption'))
        break;
        
      }
      
    }
    
  }
  
  return message;
}

function isNeedApprover(field){
  let message = [];
  let approveRule = (field.setting && field.setting.approveRule) || {};

  let {leader, level} = approveRule
  let flag = false
  if(level >= 1) {
    // 有审批但是未设置审批人
    if(!leader) flag = true

    // 不管是一级还是多级都先判断第一层的leader是否为空
    if(leader == 'users') {
      if(isEmpty(approveRule?.approves[0]?.userId)) flag = true
    }

    if(level > 1) {
      // 多级审批没有设置审批人
      let multiApproveSetting = approveRule.multiApproveSetting[level - 2];
      if(!(multiApproveSetting.leader)) flag = true
      if (multiApproveSetting.leader == 'users') {
        if(isEmpty(multiApproveSetting?.approves[0]?.userId)) flag = true
      }
    }
  }
  if(flag){ 
    message.push(t('common.validate.setApprover'))
  }
  return message;
}
/**
 * info字段的验证
 * 默认为空显示 dom.placeholder（不在此处处理)
 */
function info (field) {
  let message = [];
  
  // if(field.placeHolder && field.placeHolder.length > config.INFO_FIELD_LENGTH_MAX){
  //   message.push(`描述信息长度超过${config.INFO_FIELD_LENGTH_MAX}个字符`);
  // }

  return message;
}

function formula(fields, field) {
  let message = [];
  let formula = (field.setting && field.setting.formula) || [];
  
  // 验证是否存在已删除的无效字段
  for(let i = 0; i < formula.length; i++) {
    let index = fields.findIndex(field => field.fieldName == formula[i].value);
    let field = fields[index];
    let isDelete = !formula[i].isOperator && (!field || !!field.isHidden);

    if(isDelete){
      message.push(t('common.validate.existInvalidFields'));
      break;
    }
  }

  return message;
}
// 关联表单
function relatedTask(field){
  let message = [];
  const isShowSystemFields = field?.setting?.isShowSystemFields || false;
  const systemFields = field.setting.systemFields || []

  if(isShowSystemFields && systemFields.length == 0){
    message.push(t('common.validate.notSelectDisplayFields', {name: field.displayName}))
  }
  return message
}

// 关联表单
function relationForm(fields, field){
  let message = [];
  if(!field?.subFormFieldList?.length){
    message.push(t('common.validate.notSelectSubForm', {name: field.displayName}))
  }
  return message
}

// 连接器
function connector(fields, field){
  
  let message = [];

  const name = field.displayNameLanguage[i18n.locale] || field.displayName 

  if (!field?.setting?.connector?.toBizTypeId) {
  
    message.push(t('common.connector.validate_rule.dataSource', { name}))
    
  }

  const actionList = field?.setting?.connector?.actionList || []
  if(!actionList.every(Boolean)) {
    message.push(t('common.connector.validate_rule.interface', { name}))
  }
  
  if (isEmpty(field?.setting?.connector?.showFieldNameList)) {
    message.push(t('common.connector.validate_rule.showFieldNameList', { name}))
  }

  const subFormFieldList = field.subFormFieldList || field?.setting?.subFormFieldList || []

  const validateSubFormFieldMessage = validate(subFormFieldList)
  if(validateSubFormFieldMessage.length > 0) return validateSubFormFieldMessage.map(item=>`${item.title}-${item?.message?.join(',')}`)
  return message
}

// 子表单
function subForm(field) {
  let message = [];
  const subFormFieldList = field.subFormFieldList || field?.setting?.subFormFieldList || []

  const validateSubFormFieldMessage = validate(subFormFieldList)
  if(validateSubFormFieldMessage.length > 0) return validateSubFormFieldMessage.map(item=>`${item.title}-${item?.message?.join(',')}`)
  return message
}


// 验证关联代码块
function relatedCode(field) {
  let message = [];
  let { aliasPath ,aliasFieldName} = field?.setting?.relatedCodeTemplate || {};
  if(!aliasPath || !aliasFieldName) {
    message.push('未配置代码块');
  }
  return message;
}


// 代码块
function jsCodeBlock(fields, field){
  let message = [];
  if (!field?.setting?.codeBlockConfig?.codeContent) {
    message.push(`${field.displayName}控件未设置代码块编辑,请设置后再保存！`)

  }
  return message
}

/**
 * 验证表单字段格式
 * @param {array} fields - 待验证字段
 * @returns error message array or error message
 */
export function validate(fields){
  let noNameField = fields.map((f, i) => f.displayName ? null : i + 1).filter(i => i != null);
  if(noNameField.length > 0) return t('common.validate.requiredTitle', {data1: '', data2: noNameField.join('，')})
  // notCheckSelectVal 为不校验
  let arr = fields.filter(i=>!(i.setting && i.setting.notCheckSelectVal))
  return arr.map(field => {
    let message = common(field);

    // 服务团队不需要校验
    if(field.fieldName == 'tags') return; 

    if(isSelect(field) || isMultiSelect(field)){
      message = message.concat(select(field));
    }

    if(isQuality(field)) {
      message = message.concat(isNeedApprover(field));
    }

    if(isInfo(field)) {
      message = message.concat(info(field));
    }
    
    if (isLogisticsField(field)) {
      message = message.concat(logistics(field));
    }
    
    if(field.formType == 'formula') {
      message = message.concat(formula(fields, field));
    }

    if(field.formType == 'relationForm') {
      message = message.concat(relationForm(fields, field));
    }
    
    if (field.formType == 'connector') {
      message = message.concat(connector(fields, field));
    }

    if (field.formType == 'subForm') {
      message = message.concat(subForm(field));
    }

    if (field.formType == 'related_task') {
      message = message.concat(relatedTask(field));
    }

    // 代码块
    if (field.formType === 'jsCodeBlock') {
      message = message.concat(jsCodeBlock(fields, field));
    }

    return message.length > 0 ? {message, title: field.displayName} : null;
  }).filter(i => i != null);
}

/**
 * 默认提示，可自行根据内容提示
 * @param {string | array} message - 提示内容
 * @param {function} createElement - vue createElement function
 * @returns true - 验证成功，无提示信息。 false - 验证失败，有提示信息
 */
export function notification(message, createElement){
  if(typeof message == 'string' && message.length > 0){
    platform.notification({
      type: 'error',
      title: t('common.validate.checkTitle'),
      message
    });

    return false;
  }

  if(Array.isArray(message) && message.length > 0){
    platform.notification({
      type: 'error',
      title: t('common.validate.checkField'),
      duration: 0,
      message: (function(h) {
        let content = message.map(i => {
          let nodes = i.message.map(m => <p>- {m}</p>);
          nodes.unshift(<h3>{i.title}</h3>)
          return nodes;
        })

        return (
          <div class="form-design-notification">{content}</div>
        )
      })(createElement)
    }) 
    return false;
  }

  return true
}